/**
 * 
 */
package pe.gob.foncodes.ssa.web.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.FactoryFinder;
import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @author Jesus
 * 
 */
public class JSFUtil {

	public static int longitudCampos = 36;
	
	private static ResourceBundle getBundle() {
		FacesContext ctx = FacesContext.getCurrentInstance();
		UIViewRoot uiRoot = ctx.getViewRoot();
		Locale locale = uiRoot.getLocale();
		ClassLoader ldr = Thread.currentThread().getContextClassLoader();
		return ResourceBundle.getBundle(
				ctx.getApplication().getMessageBundle(), locale, ldr);
	}

	public static String getStringFromBundle(String key) {
		ResourceBundle bundle = getBundle();
		return bundle.getString(key);
	}

/*	public static String getStringMessage(String key) {
		ResourceBundle bundle = ResourceBundle.getBundle(Constantes.RESOURCE_MESSAGE_ERROR);
		return bundle.getString(key);
	}*/
	
	public static void setViewRootLocale(Locale locale) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		UIViewRoot uiRoot = ctx.getViewRoot();
		uiRoot.setLocale(locale);
	}

	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) FacesContext.getCurrentInstance()
				.getExternalContext().getRequest();
	}

	public static HttpSession getSession() {
		return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	}
	
	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) FacesContext.getCurrentInstance()
				.getExternalContext().getResponse();
	}

	public static String getRequestServerName() {
		return getRequest().getServerName();
	}

	public static String getRequestURI() {
		return getRequest().getRequestURI();
	}

	public static String getRequestQueryString() {
		return getRequest().getQueryString();
	}

	public static Locale getRequestLocale() {
		return getRequest().getLocale();
	}

	public static String getRequestUserAgent() {
		return getRequest().getHeader("User-Agent");
	}

	/**
	 * switches from HTTP to HTTPS or back if used to go from HTTPS to HTTP
	 * older browsers (like IE 6) could complain so use carefully
	 */
	public static void switchHTTPSecurity() throws IOException {
		HttpServletRequest req = getRequest();
		StringBuffer sb = new StringBuffer();
		if (req.isSecure())
			sb.append("http://");
		else
			sb.append("https://");
		sb.append(req.getServerName()).append(req.getRequestURI());
		if (req.getQueryString() != null)
			sb.append("?").append(req.getQueryString());
		JSFUtil.sendRedirect(sb.toString());
	}

	public static void sendRedirect(String URL) throws IOException {
		HttpServletResponse response = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		FacesContext.getCurrentInstance().responseComplete();
		response.sendRedirect(URL);
	}
	
	public static void sendRedirectToCotext(String URL) throws IOException {
		ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
		FacesContext.getCurrentInstance().responseComplete();
		ec.redirect(ec.getRequestContextPath()+URL);
	}

	public static void setPageNotFound() throws IOException {
		HttpServletResponse response = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		response.setStatus(HttpServletResponse.SC_NOT_FOUND);
	}

	public static String getRemoteAdress() {
		String s = "";
		try {
			HttpServletRequest request = getRequest();
			String hostname = "";
			try {
				InetAddress addr = InetAddress.getByName(request
						.getRemoteHost());
				hostname = addr.getHostName();
			} catch (UnknownHostException e) {
			}

			s = (hostname + "_" + request.getRemoteHost() + "_" + request
					.getRemoteAddr());
			s = s.substring(0, 50);
		} catch (Exception e) {
		}
		return s;
	}

	

	public static void addInfo(String msg, String title) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_INFO, title, msg));
	}

	public static void addWarn(String msg, String title) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_WARN, title, msg));
	}

	public static void addError(String msg, String title) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, title, msg));
	}

	public static void addFatal(String msg, String title) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_FATAL, title, msg));
	}

	public static ServletContext getServletContext() {
		return (ServletContext) FacesContext.getCurrentInstance()
				.getExternalContext().getContext();
	}

	public static void respuestacompleta() {
		FacesContext context = FacesContext.getCurrentInstance();
		context.responseComplete();
	}

	public static void redirect(String url) throws IOException {
		FacesContext.getCurrentInstance().getExternalContext().redirect(url);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object getExpresion(String el, Class clase) {
		FacesContext context = FacesContext.getCurrentInstance();
		return context.getApplication().evaluateExpressionGet(context, el,
				clase);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object getExpresionServlet(String el, Class clase,HttpServletRequest request, HttpServletResponse response){
	 FacesContext facesContext = FacesContext.getCurrentInstance();
	 if(facesContext==null){
		FacesContextFactory contextFactory  = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
     	LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); 
     	Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);     
     	facesContext = contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);
	 }
     FacesContext context = FacesContext.getCurrentInstance();
     
     return context.getApplication().evaluateExpressionGet(context, el,		clase);
     }
	
	public static void sendRedirectnavigationHandler(String URL) throws IOException {
		FacesContext facesContext = FacesContext.getCurrentInstance(); 
        NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler(); 
        navigationHandler.handleNavigation(facesContext, null, URL); 
	}	
	public static String getUserName(){
		FacesContext context = FacesContext.getCurrentInstance();
		return getRequest().getUserPrincipal().getName();
	}

	public static ExternalContext getExternalContext(){
		return FacesContext.getCurrentInstance().getExternalContext();
	}
	

}
